package org.example.filter;


import io.jsonwebtoken.Claims;
import org.example.cache.RedisCache;
import org.example.entity.User;
import org.example.entity.vo.LoginUser;
import org.example.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * Copyright: Copyright (c) 2022 Asiainfo
 *
 * @ClassName: com.zxp.springsecurity.filter.JwtAuthenticationTokenFilter
 * @Description: 该类的功能描述
 * @version: v1.0.0
 * @author: 炫沙糖桔的鹏仔
 * @date: 2022/8/9 8:48
 * <p>
 * Modification History:
 * Date         Author          Version            Description
 * ------------------------------------------------------------
 * 2022/8/9      炫沙糖桔的鹏仔          v1.0.0               修改原因
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisCache redisCache;
    /**
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {
//        获取token
        String token = request.getHeader("token");
//        如果token为空,直接放行 后续还有过滤器
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }
//        解析token
        Object id;
        try {
            Claims claims = JwtUtils.parseToken(token);
             id = claims.get("Id");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token解析失败");
        }
//        从redis获取用户信息
        String key = "login:" + id;
        LoginUser cacheObject = redisCache.getCacheObject(key);
//        存入seccurityContextHolder
        if (Objects.isNull(cacheObject)) {
            throw new RuntimeException("用户不存在");
        }
        UsernamePasswordAuthenticationToken
                authentication =
                new UsernamePasswordAuthenticationToken(cacheObject,null,cacheObject.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }
}


